/**
 *	Kernel of the "driver"
 *
 * 	While prints codes of keys.
 *
 */


#include <stdio.h>
#include <iostream>
//#include <unistd.h>
//#include <sys/types.h>
#include <sys/wait.h>
#include <libusb-1.0/libusb.h>

#define VERBOSE_DEBUG 	3
#define VENDOR_ID		0x147a
#define PRODUCT_ID		0xe02f

#define MYDEBUG			1


void read_keys(libusb_device_handle* dh);

int main() {
	int r; // return code
	if (MYDEBUG) {
		printf(">> Creating context...\t\t");
	}
	libusb_context* ctx;
	if (libusb_init(&ctx)<0) {
		printf("Context create error!\n");
		return 1;
	}
	
	libusb_set_debug(ctx,VERBOSE_DEBUG);

	libusb_device_handle* dh;
	if (MYDEBUG) { 
		printf("OK\n");
		printf(">> Opening device...\t\t");
	}
	
	dh = libusb_open_device_with_vid_pid(ctx, VENDOR_ID, PRODUCT_ID);
	if (dh == NULL) {
		printf("Device not found\n");
		return 1;
	}
	
	//r = libusb_detach_kernel_driver(dh, 0);
	//printf("rc : %d\n", r);

	if (MYDEBUG) { 
		printf("OK\n");
		printf(">> Claiming interface...\t");
	}
	r =	libusb_claim_interface(dh, 0);
	if (r != 0) {
		printf("Error in claim interface : %d\n", r);
		return -1;
	}
	if (MYDEBUG) { 
		printf("OK\n");
	}


	pid_t pid = fork();
	if (!pid) {
		read_keys(dh);
	//	for (int i=0; i<2000000000; i++);
		return 0;
	}
	printf("Before wait...\n");
	int tt = wait(&r);
	printf("%d %d\n", tt, r);
	printf("After wait\n");

	if (MYDEBUG) {
		printf(">> Releasing interface...\t");
	}
	r =	libusb_release_interface(dh, 0);
	if (r != 0) {
		printf("Error in release interface\n");
		return -1;
	}
	if (MYDEBUG) {
		printf("OK\n");
	}
	MYDEBUG ? printf(">> Closing...\t\t\tOK\n"):0;
	libusb_close(dh);
	MYDEBUG ? printf(">> Exiting...\t\t\tOK\n"):0;
	libusb_exit(ctx);
	return 0;
};

void read_keys( libusb_device_handle* dh ) {
	int length = 0;
	int r;
	unsigned char data[3];
	while (true) {
		printf("Please, press the key ...\n");
		r = libusb_interrupt_transfer(dh, 129, data, sizeof(data), &length, 0);
		printf("rc : %d\t\nFirstRequest\t %d:%d:%d\n",r,data[0],data[1],data[2]);
		
		r = libusb_interrupt_transfer(dh, 129, data, sizeof(data), &length, 0);
		printf("rc : %d\t\nSecondRequest\t %d:%d:%d\n",r,data[0],data[1],data[2]);	
	}
};
